<?php
// +----------------------------------------------------------------------
// | snake
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2022 http://baiyf.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: NickBai <1902822973@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;


use app\admin\model\RoleModel;
use app\admin\model\MemberModel;
use think\Validate;

class Member extends Base
{
    //用户列表
    public function index()
    {
        if(request()->isAjax()){

            $param = input('param.');

            $limit = $param['pageSize'];
            $offset = ($param['pageNumber'] - 1) * $limit;

            $where = [];
            if (!empty($param['searchText'])) {
                $where[] = ['memb_phone', 'like', '%' . $param['searchText'] . '%'];
            }
            if (!empty($param['status']) || $param['status'] == '0') {
                $where[] = ['memb_is_truth', '=', $param['status']];
            }
            $user = new MemberModel;
            $selectResult = $user->getUsersByWhere($where, $offset, $limit);

            // 拼装参数
            foreach($selectResult as $key=>$vo){

                $selectResult[$key]['is_truth'] = $vo['is_truth'];
                $selectResult[$key]['status'] = $vo['status'];

                $selectResult[$key]['operate'] = showOperate($this->makeButton($vo['memb_id']));
            }

            $return['total'] = $user->getAllUsers($where);  //总数据
            $return['rows'] = $selectResult;

            return json($return);
        }
        $giveMoney = db('config')->where('name', 'givemoney')->find();
        $this->assign('config', $giveMoney);
        // dump(cache(session('role_id')));
        return $this->fetch();
    }

    public function changeConfig(){
        $info = input('post.');
        $validate = Validate::make([
            'status' => 'require',
            'money|金额'    => 'integer|>:0|requireIf:status, 0'
        ]);
        if(!$validate->check($info)){
            return json(msg(-1, '', $validate->getError()));
        }
        if($info['status']){// 关闭
            $param = [
                'status'    => 0,
            ];
            $data = ['btn'=>'开启', 'status'=>0];
        }else{//开启
            $param = [
                'status'    => 1,
                'value'     => $info['money'],
            ];
            $data = ['btn'=>'关闭', 'status'=>1];
        }
        try {
            db('config')->where('name', 'givemoney')->update($param);
            return json(msg(1, $data, '修改成功'));
        } catch (\Throwable $th) {
            throw $th;
        }
    }

    // 编辑用户
    public function edit()
    {
        $user = new MemberModel();

        if(request()->isPost()){

            $param = [
                'memb_id'        => input('post.id'),
                'memb_is_truth'    => input('post.is_truth'),
                'memb_black'=> input('post.status'),
            ];
            if(input('post.is_truth') == 0){
                $param['memb_truename'] = '';
                $param['memb_cardImage'] = '';
            }
            
            $flag = $user->editUser($param);

            return json(msg($flag['code'], $flag['data'], $flag['msg']));
        }

        $id = input('id');
        
        return $this->fetch('edit', ['member'=>MemberModel::find($id)]);
    }

    // 删除用户
    public function del()
    {
        $id = input('param.id');

        $role = new MemberModel();
        $flag = $role->delUser($id);
        return json(msg($flag['code'], $flag['data'], $flag['msg']));
    }

    // 金额充值
    public function recharge(){
        $uid = input('post.uid');
        $desc = input('desc');
        $value = intval(input('post.value'));
        if($uid && $value && $desc){
            $balance = MemberModel::where('memb_id', $uid)->value('memb_balance');
            if($value + $balance < 0){
                return json(msg(-2, '', '修改失败，最终余额小于0'));
            }
            \app\index\model\Member::updateBalance($uid, $value, $desc);
            return json(msg(1, '', '更新成功'));
        }else{
            return json(msg(-1, '','404，页面错误'));
        }
    }

    /**
     * 拼装操作按钮
     * @param $id
     * @return array
     */
    private function makeButton($id)
    {
        return [
            '编辑' => [
                'auth' => 'member/edit',
                'href' => url('member/edit', ['id' => $id]),
                'btnStyle' => 'primary',
                'icon' => 'fa fa-paste'
            ],
            '充值' => [
                'auth' => 'member/recharge',
                'href' => "javascript:recharge(" .$id .")",
                'btnStyle' => 'danger',
                'icon' => 'fa fa-paste'
            ],
        ];
    }
}
